package main

import (
	"bufio"
	"compress/zlib"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
	"time"
)

// 1. 把字符串1998-10-01 08:10:00解析成time.Time，再格式化成字符串19981001081000
// 2. 我们是每周六上课，输出我们未来4次课的上课日期（不考虑法定假日）
// 3. 把一个目录下的所有.txt文件合一个大的.txt文件，再对这个大文件进行压缩
// 4. 自己实现一个BufferedFileWriter

type BufferedFileWriter struct {
	buffer      [1024]byte
	endPos      int
	fileHandler *os.File
}

func NewBufferFileWriter(fd *os.File) *BufferedFileWriter {
	return &BufferedFileWriter{
		fileHandler: fd,
	}
}

func (writer *BufferedFileWriter) Flush() {
	if writer.endPos >= 0 {
		writer.fileHandler.Write(writer.buffer[:writer.endPos])
		writer.endPos = 0
	}
}

func (writer *BufferedFileWriter) Write(content []byte) {
	if len(content) >= 1024 {
		writer.fileHandler.Write(content)
	} else {
		if writer.endPos+len(content) >= 1024 {
			writer.Flush()
			writer.Write(content)
		} else {
			copy(writer.buffer[writer.endPos:], content)
			writer.endPos += len(content)
		}
	}
}

func (writer *BufferedFileWriter) WriteString(str string) {
	writer.Write([]byte(str))
}

func Question1() {
	format1 := "2006-01-02 15:04:05"
	format2 := "20060102150405"

	str1 := "1998-10-01 08:10:00"
	loc, _ := time.LoadLocation("Asia/Shanghai")
	t, _ := time.ParseInLocation(format1, str1, loc)
	str2 := t.Format(format2)
	fmt.Println(str2)
}

func Question2() {
	now := time.Now()
	sub := 6 - now.Weekday()
	interval := sub
	if sub == 0 {
		interval = 7
	}

	next1 := now.Add(time.Duration(interval) * time.Hour * 24)
	next2 := next1.Add(7 * time.Hour * 24)
	next3 := next2.Add(7 * time.Hour * 24)
	next4 := next3.Add(7 * time.Hour * 24)

	fmt.Printf("未来四次课的日期为 %s %s %s %s\n", next1.Format("2006-01-02"), next2.Format("2006-01-02"), next3.Format("2006-01-02"), next4.Format("2006-01-02"))
}

func Question3() {
	fout, err := os.OpenFile("merge.txt", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, os.ModePerm)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer fout.Close()

	writer := bufio.NewWriter(fout)

	compress, err := os.OpenFile("merge.zlib", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, os.ModePerm)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer compress.Close()

	zipWriter := zlib.NewWriter(compress)

	if files, err := os.ReadDir("dir"); err != nil {
		fmt.Println(err)
		return
	} else {
		for _, file := range files {
			if file.IsDir() {
				continue
			}
			baseName := file.Name()
			if strings.HasSuffix(baseName, ".txt") {
				if fin, err := os.Open(filepath.Join("dir", baseName)); err != nil {
					fmt.Println(err)
					return
				} else {
					defer fin.Close()
					reader := bufio.NewReader(fin)
					for {
						if line, err := reader.ReadString('\n'); err != nil {
							if err == io.EOF {
								// if len(line) > 0 {
								writer.WriteString(line)
								writer.WriteString("\n")
								zipWriter.Write([]byte(line))
								zipWriter.Write([]byte("\n"))
								// }
							}
							break
						} else {
							writer.WriteString(line)
							zipWriter.Write([]byte(line))
						}
					}
				}
			}
		}
	}

	writer.Flush()
}

func Question4() {
	fout, err := os.OpenFile("test.txt", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, os.ModePerm)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer fout.Close()

	buffWriter := NewBufferFileWriter(fout)
	for i := 0; i < 10; i++ {
		buffWriter.WriteString("这是一次测试写入\n")
	}

	buffWriter.Flush()
}

func main() {
	Question1()
	Question2()
	Question3()
	Question4()
}
